import axios from 'axios'
import { Message } from 'element-ui'

axios.defaults.baseURL = '/idispatch'

axios.interceptors.request.use(
  (config) => {
    const tokenSign = sessionStorage.getItem('tokenSign')
    if (!config.login && tokenSign) {
      config.headers.Authorization = tokenSign
      return config
    } else Message.warning('连接调度台接口失败')
  },
  (error) => {
    if (sessionStorage.getItem('tokenSign')) {
      return Promise.reject(error)
    }
  }
)

axios.interceptors.response.use(
  (response) => {
    // console.log(
    //   'response.data',
    //   response.config.url,
    //   JSON.stringify(response.data)
    // );
    if (response == undefined) {
      Message.warning('调度台已退出，将影响部分功能使用，请重新登录')
    }
    if (
      response.data.msg === 'fail' &&
      (response.data.reason == 'user_logout' ||
        response.data.reason == 'The_user_is_not_login' ||
        response.data.reason == "'NoneType' object has no attribute 'operator'")
    ) {
      sessionStorage.clear()
      Message.warning(response.data.reason)
      // Message.warning('调度台已退出，请重新登录')
    } else if (
      (response.data.msg == 'fail' || response.data.reason == 'fail') &&
      sessionStorage.getItem('tokenSign')
    ) {
      // Message.warning(response.data.reason)
      Message.warning('调度台已退出，将影响部分功能使用，请重新登录')
    } else {
      return Promise.resolve(response)
    }
  },
  (error) => {
    if (error.request.status === 500) {
      // 连接服务器失败
      sessionStorage.clear()
      return Promise.reject('连接服务器失败')
    }
    return Promise.reject(error)
  }
)

export default axios
